/*
 * Filename: g:\espidf_workspace\idf_S3_T-Watch\main\devices\rtc_clock.cc
 * Path: g:\espidf_workspace\idf_S3_T-Watch\main\devices
 * Created Date: Friday, June 20th 2025, 3:26:27 pm
 * Author: sss
 *
 * Copyright (c) 2025 Your Company
 */

#include "rtc_clock.h"
#include "sensor_bus.h"

#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "SensorPCF8563.hpp"

static const char *TAG = "RTC_CLOCK";

static SensorPCF8563 rtc;

RTC_Clock::RTC_Clock() {}
RTC_Clock::~RTC_Clock() {}

void RTC_Clock::init()
{
    i2c_master_bus_handle_t i2c_bus_handle = get_i2c_bus_handle();
    if (rtc.begin(i2c_bus_handle, PCF8563_SLAVE_ADDRESS))
    {
        ESP_LOGI(TAG, "rtc begin success");
        // rtc_inited = true;
    }
}
time_t RTC_Clock::now_system_time(){
    time_t t = time(nullptr);
    timeinfo = localtime(&t);
    
    ESP_LOGI(TAG, "rtc current time %d-%d-%d %d:%d:%d", timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
    return t;
}
time_t RTC_Clock::now()
{
    rtc.getDateTime(timeinfo);

    ESP_LOGI(TAG, "rtc current time %d-%d-%d %d:%d:%d", timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
    return mktime(timeinfo);
}

void RTC_Clock::set_time(time_t t)
{
    // 转换为 time_t 并设置系统时间
    struct timeval now = {.tv_sec = t};
    settimeofday(&now, NULL);
    ESP_LOGI("RTC", "system time set to: %s", ctime(&t));
}
void RTC_Clock::set_time()
{
    time_t t = now();
    set_time(t);
}

void RTC_Clock::set_time_RTC(time_t t)
{
    timeinfo = localtime(&t);
    uint16_t year = (uint16_t)timeinfo->tm_year + 1900;
    uint8_t month = (uint8_t)timeinfo->tm_mon + 1;
    uint8_t day = (uint8_t)timeinfo->tm_mday;
    uint8_t hour = (uint8_t)timeinfo->tm_hour;
    uint8_t minute = (uint8_t)timeinfo->tm_min;
    uint8_t second = (uint8_t)timeinfo->tm_sec;
    rtc.setDateTime(year, month, day, hour, minute, second);

    ESP_LOGI("RTC", "Internal RTC set to: %s", ctime(&t));
}
